<template>
    <div class="im-container">
        <div class="session-list">
            <div class="session-title">会话列表</div>
            <el-scrollbar class="session-scroll">
                <div v-for="session in sessions" :key="session.userId"
                    :class="['session-item', session.userId === currentUserId ? 'active' : '']"
                    @click="selectSession(session)">
                    <el-avatar :src="session.user && session.user.avatar ? getImageUrl(session.user.avatar) : ''"
                        size="medium" icon="el-icon-user-solid" />
                    <div class="session-info">
                        <div class="name">{{ session.user && session.user.name }}</div>
                        <div class="desc">{{ session.user && session.user.email }}</div>
                    </div>
                </div>
                <el-empty v-if="!sessions.length" description="暂无会话" />
            </el-scrollbar>
        </div>
        <div class="chat-area" v-if="currentUserId">
            <div class="chat-header">
                <span>{{ currentSession.user && currentSession.user.name }}</span>
                <span class="chat-title-desc">{{ currentSession.user && currentSession.user.email }}</span>
            </div>
            <div class="chat-messages" ref="msgBox">
                <div v-for="msg in messages" :key="msg.id" :class="['chat-msg', msg.fromExpert ? 'right' : 'left']">
                    <el-avatar
                        :src="msg.fromExpert ? getImageUrl(expertInfo.avatar) : (currentSession.user && getImageUrl(currentSession.user.avatar))"
                        size="small" icon="el-icon-user-solid" />
                    <div class="bubble">
                        <span class="role">{{ msg.fromExpert ? '[我]' : '[用户]' }}</span>
                        <span>{{ msg.content }}</span>
                        <span class="time">{{ formatTime(msg.sendTime) }}</span>
                    </div>
                </div>
            </div>
            <div class="chat-input-row">
                <el-input v-model="input" placeholder="请输入内容..." @keyup.enter.native="send" class="chat-input" />
                <el-button type="primary" @click="send">发送</el-button>
            </div>
        </div>
        <div class="chat-area" v-else>
            <el-empty description="请选择会话" />
        </div>
    </div>
</template>
<script>
import { getExpertSessions, getHistory } from '../api/ChatController';
import { sendChatMessage, connectChatSocket, closeChatSocket } from '../api/chatSocket';
import { getExpertDetail } from '../api/ExpertController';
export default {
    data() {
        return {
            expertInfo: {},
            sessions: [],
            currentUserId: null,
            currentSession: {},
            //messages: [],
            messagesMap: {}, // { expertId: [msg, ...] }
            input: ''
        };
    },
    methods: {
        async loadSessions() {
            const res = await getExpertSessions(this.expertInfo.id);
            this.sessions = Array.isArray(res) ? res : (res.data || []);
            if (this.sessions.length) {
                this.selectSession(this.sessions[0]);
            }
        },
        handleSocketMessage(msg) {
            console.log('专家端收到消息', msg, this.expertInfo.id);
            if (!msg || msg.expertId != this.expertInfo.id) return; // 用 == 或都转字符串
            // 假设你用 messagesMap 存储每个会话的消息
            const userId = msg.userId;
            if (!this.messagesMap) this.messagesMap = {};
            if (!this.messagesMap[userId]) this.$set(this.messagesMap, userId, []);
            this.messagesMap[userId].push(msg);
            if (this.currentUserId === userId) {
                this.$nextTick(this.scrollToBottom);
            }
        },
        async selectSession(session) {
            this.currentUserId = session.userId;
            this.currentSession = session;
            // 拉取历史消息
            const res = await getHistory({ userId: session.userId, expertId: this.expertInfo.id });
            this.$set(this.messagesMap, session.userId, Array.isArray(res) ? res : (res.data || []));
            this.$nextTick(this.scrollToBottom);
        },
        send() {
            if (!this.input) return;
            const msg = {
                expertId: this.expertInfo.id,
                userId: this.currentUserId,
                content: this.input,
                fromExpert: true,
                sendTime: new Date().toISOString()
            };
            sendChatMessage(msg);
            //this.messages.push(msg);
            this.input = '';
            this.$nextTick(this.scrollToBottom);
        },
        scrollToBottom() {
            const box = this.$refs.msgBox;
            if (box) box.scrollTop = box.scrollHeight;
        },
        getImageUrl(url) {
            if (!url) return '';
            return url.startsWith('/api') ? url : `/api${url}`;
        },
        formatTime(time) {
            if (!time) return '';
            if (typeof time === 'string') {
                // 兼容 ISO 字符串和 yyyy-MM-dd HH:mm:ss
                if (time.includes('T')) {
                    return time.replace('T', ' ').substring(0, 19);
                }
                return time.substring(0, 19);
            }
            if (typeof time === 'number') {
                // 毫秒时间戳
                const date = new Date(time);
                const pad = n => n < 10 ? '0' + n : n;
                return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
            }
            if (time instanceof Date) {
                const pad = n => n < 10 ? '0' + n : n;
                return `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())} ${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())}`;
            }
            return String(time);
        },
    },
    async mounted() {
        this.expertInfo = JSON.parse(localStorage.getItem('backUser') || '{}');
        console.log('专家端建立 WebSocket 连接', this.expertInfo.id);
        const data = await getExpertDetail(this.expertInfo.id); // 通过 userId 查专家表
        this.expertInfo.avatar = data.expert.avatar;
        console.log(this.expertInfo);
        this.loadSessions();
        connectChatSocket({
            expertId: this.expertInfo.id, // 这里必须是专家表 userId
            userId: this.expertInfo.id,   // 这里也必须是专家表 userId
            role: 'expert',
            onMessage: this.handleSocketMessage.bind(this)
        });
    },
    computed: {
        messages() {
            return this.messagesMap[this.currentUserId] || [];
        }
    },
    beforeDestroy() {
        closeChatSocket();
    }
};
</script>
<style scoped>
.im-container {
    display: flex;
    width: 100%;
    max-width: 1100px;
    min-height: 600px;
    margin: 40px auto;
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 4px 24px #e6e8f0;
    overflow: hidden;
}

.session-list {
    width: 240px;
    background: #f7f8fa;
    border-right: 1px solid #e6e8f0;
    display: flex;
    flex-direction: column;
}

.session-title {
    font-size: 18px;
    font-weight: bold;
    padding: 18px 20px 10px 20px;
    border-bottom: 1px solid #e6e8f0;
}

.session-scroll {
    flex: 1;
    padding: 10px 0;
}

.session-item {
    display: flex;
    align-items: center;
    padding: 12px 18px;
    cursor: pointer;
    border-radius: 8px;
    margin: 4px 8px;
    transition: background 0.2s;
}

.session-item.active,
.session-item:hover {
    background: #e6f7ff;
}

.session-info {
    margin-left: 12px;
}

.session-info .name {
    font-weight: bold;
    font-size: 15px;
}

.session-info .desc {
    color: #888;
    font-size: 13px;
}

.chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
    max-height: 800px;
    overflow: auto;
}

.chat-header {
    font-size: 17px;
    font-weight: bold;
    padding: 18px 24px;
    border-bottom: 1px solid #e6e8f0;
    display: flex;
    align-items: center;
    gap: 16px;
}

.chat-title-desc {
    color: #409EFF;
    font-size: 14px;
    font-weight: normal;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 18px 24px;
    background: #f7f8fa;
}

.chat-msg {
    display: flex;
    margin-bottom: 14px;
    align-items: flex-end;
}

.chat-msg.left {
    flex-direction: row;
}

.chat-msg.right {
    flex-direction: row-reverse;
}

.bubble {
    max-width: 60%;
    background: #fff;
    border-radius: 16px;
    padding: 10px 16px;
    font-size: 15px;
    margin: 0 10px;
    box-shadow: 0 2px 8px #e6e8f0;
    word-break: break-all;
}

.chat-msg.right .bubble {
    background: #cce6ff;
}

.role {
    font-weight: bold;
    margin-right: 6px;
    color: #409EFF;
}

.time {
    font-size: 12px;
    color: #888;
    margin-left: 8px;
}

.chat-input-row {
    display: flex;
    gap: 10px;
    align-items: center;
    padding: 18px 24px;
    border-top: 1px solid #e6e8f0;
    background: #fff;
}

.chat-input {
    flex: 1;
}
</style>